﻿using K8.LSF;

namespace KingerRobot.MexicoSailunWMS.SpiService;

internal class BRcsEquipBuilding : IRcsEquipBuilding
{
    private readonly static IRcsEquip _rcsEquip = new BRcsEquip();

    public List<PORcsEquipBuilding> GetAllEquipBuildings()
    {
        var db = Db.Default;
        //查找成型机
        var result = db.RcsEquipBuildings
            .Join(db.RcsEquips, f => f.Id, s => s.Id, (f, s) => new { Building = f, Equip = s })
            .Select(t => t.Building)
            .ToList();
        return result;

    }

    public int GetEquipCrashStatus()
    {
        var db = Db.Default;
        int result;
        result = db.RcsEquipBuildings.Where(t => t.UseFlag == 1).FirstOrDefault()?.CrashStatus ?? (int)EnumCarshStatus.Normal;
        return result;
    }

    public int UpdateEquipCrashStatusById(long id)
    {
        var db = Db.Default;
        int result;
        var building = db.RcsEquipBuildings.Where(t => t.Id == id).FirstOrDefault();
        if(building is null)
        {
            return -2;
        }
        result = db.RcsEquipBuildings.Where(t => t.Id == id).Update( new PORcsEquipBuilding
        {
            CrashStatus = building.CrashStatus == 1 ? 0 : 1,
            CrashTime = building.CrashStatus == 1 ? building.CrashTime : DateTime.Now
        });
        return result;
    }
    public int UpdateCrashStatus(bool syncChange)
    {
        var result = 0;
        var db = Db.Default;
        var building = db.RcsEquipBuildings.Where(t => true);
        var ids = building.Select(t => t.Id).ToList();

        if (building.FirstOrDefault().CrashStatus == 1)//当前是宕机 从宕机变为可用
        {
            result = building.Update( new PORcsEquipBuilding
            {
                CrashStatus = 0,
                CrashTime = null,
                UpdateTime = DateTime.Now,
            });
            if (syncChange)
            {
                result = _rcsEquip.UpdateEquipEnableByIds(ids, 1);
            }

        }
        else//从可用变为宕机
        {
            result = building.Update( new PORcsEquipBuilding
            {
                CrashStatus = 1,
                CrashTime = DateTime.Now,
                UpdateTime = DateTime.Now,
            });
            result = _rcsEquip.UpdateEquipEnableByIds(ids, 0);
        }
        result = result == 0 ? 0 : 1;
        return result;
    }



}
